package my.leetcode.solution;

public class P9 {

    public static void main(String[] args) {
        System.out.println(isPalindrome(1410110141) + "");
        System.out.println(isPalindrome(1001) + "");
        System.out.println(isPalindrome(1221) + "");
        System.out.println(isPalindrome(12321) + "");
        System.out.println(isPalindrome(123321) + "");
        System.out.println(isPalindrome(123421) + "");
    }


    public static int pow10(int n) {
        int r = 1;
        for(int i = 0;i < n;i++) {
            r*=10;
        }
        return r;
    }

    public static int numberBitCount(int n) {
        int r = 100000;
        if(r > n) {
            r = 10;
            for(int i = 1;i < 5;i++) {
                if(n < r) {
                    return i;
                }
                r *=10;
            }
            return 5;
        } else {
            r *=10;
            for(int i = 6;i < 10;i++) {
                if(n < r) {
                    return i;
                }
                r *=10;
            }
            return 10;
        }
    }

    public static boolean isPalindrome(int n) {
        if(n < 0) {
            return false;
        }
        if(n < 10) {
            return true;
        }
        int t, size = numberBitCount(n), scale = pow10(size / 2),
                high = n / ((size & 1) == 1 ? scale * 10 : scale),
                low = n % scale, r = 10;
        while ((t = scale / r) > 0) {
            if(high % 10 != (low / t) % 10) {
                return false;
            }
            high /= 10;
            r*=10;
        }
        return true;
    }


}
